package org.tacticalTroopers.jme.server;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tacticalTroopers.jme.common.message.Command;
import org.tacticalTroopers.jme.common.message.Information;
import org.tacticalTroopers.jme.server.object.ServerGameArea;
import org.tacticalTroopers.jme.server.object.ServerPlayer;

import com.jme3.network.connection.Client;
import com.jme3.network.message.Message;



public class NetworkClientHandler {

	final static Log log = LogFactory.getLog(NetworkClientHandler.class);

	Client client;
	ServerPlayer player;
	TacticalTroopersServer server;
	
	public NetworkClientHandler(Client s,TacticalTroopersServer server) {
		this.client = s;
		this.server=server;
	}


	
	
	public void sendGameState(ServerGameArea serverGameArea)  {
		send(serverGameArea.getGameState().getGameStateMessage());
	}

	void send(Message m){
		try {
			client.send(m);
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
		}	
	}
	
	void sendNotCatched(Message m) throws IOException{
		client.send(m);
	}


	public ServerPlayer getPlayer() {
		return player;
	}


	public void initPlayer(ServerPlayer p) {
		p.setNetworkClientHandler(this);
		player = p;
		send(p.getId());
	}


	public void initGameArea(ServerGameArea gameArea) {
		send(gameArea.getMap().getGameMapMessage());
	}




	public void receiveMessage(Message message) {
		if(message instanceof Command){
			player.getCommand().set((Command)message);
		}else if (message instanceof Information){
			Information info = (Information)message;
			if(info.getKey().equals("playerName")){
				Integer i = player.getId().getValue();
				String name = info.getValue();
				//log.info("Server Receive playerName:"+name);
				server.getPlayerManager().setPlayerName(i,name);
			}
		
		}
	}
	
	public Boolean wantToQuit(){
		return player.getCommand().getOrder().equals(Command.QUIT);
	}



	








}
